package org.example.chatroom.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.val;
import org.example.chatroom.common.pojo.dataobject.Friend;
import org.example.chatroom.common.pojo.dataobject.FriendRequest;
import org.example.chatroom.common.pojo.dataobject.UserInfo;
import org.example.chatroom.common.pojo.request.AddFriendRequest;
import org.example.chatroom.common.pojo.request.FriendSearchRequest;
import org.example.chatroom.common.pojo.response.FriendResponse;
import org.example.chatroom.common.pojo.response.FriendSearchResponse;
import org.example.chatroom.common.pojo.response.WebSocketFriendRequestResponse;
import org.example.chatroom.mapper.FriendMapper;
import org.example.chatroom.mapper.FriendRequestMapper;
import org.example.chatroom.mapper.UserMapper;
import org.example.chatroom.service.FriendService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2025-06-22
 * Time: 23:58
 */
@Service
public class FriendServiceImpl implements FriendService {
    private static final Integer NORMAL_USER = 0;
    private static final Integer ABNORMAL_USER = 1;
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FriendRequestMapper friendRequestMapper;
    @Override
    public List<FriendResponse> getfriendlist(Integer userId) {
        //首先获得id列表
        QueryWrapper<Friend> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(Friend::getUserId,userId);
        List<Friend> friends = friendMapper.selectList(queryWrapper);


        List<FriendResponse> friendResponses = friends.stream().map(friend -> {
            FriendResponse friendResponse = new FriendResponse();
            QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper();
            queryWrapper1.lambda().eq(UserInfo::getDeleteFlag,NORMAL_USER)
                    .eq(UserInfo::getId,friend.getFriendId());
            UserInfo userInfo = userMapper.selectOne(queryWrapper1);
            BeanUtils.copyProperties(userInfo,friendResponse);
            return friendResponse;
        }) .collect(Collectors.toList());

        return friendResponses;
    }

    @Override
    public List<FriendSearchResponse> searchFriends(FriendSearchRequest request) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getDeleteFlag,NORMAL_USER)
                .eq(UserInfo::getUserName,request.getUserName());
        List<UserInfo> userInfos = userMapper.selectList(queryWrapper);
        List<FriendSearchResponse> friendSearchResponses = userInfos.stream().map(userInfo -> {
            FriendSearchResponse friendSearchResponse = new FriendSearchResponse();
            BeanUtils.copyProperties(userInfo,friendSearchResponse);
            return friendSearchResponse;
        }).collect(Collectors.toList());
        return friendSearchResponses;
    }


    @Override
    public void handleFriendRequest(Integer userId, Integer friendRequestId, String action) {
        FriendRequest friendRequest = friendRequestMapper.selectById(friendRequestId);
        if(friendRequest != null && friendRequest.getToUserId().equals(userId)){
            if("accept".equals(action)){
                //添加好友关系
                Friend friend1 = new Friend();
                friend1.setUserId(userId);
                friend1.setFriendId(friendRequest.getFromUserId());
                Friend friend2 = new Friend();
                friend2.setUserId(friendRequest.getFromUserId());
                friend2.setFriendId(userId);
                friendMapper.insert(friend1);
                friendMapper.insert(friend2);
                //更改请求状态
                friendRequest.setStatus(action);
            }else if("reject".equals(action)){
                //拒绝
                friendRequest.setStatus(action);
            }
            friendRequestMapper.updateById(friendRequest);
        }

    }

    @Override
    public List<WebSocketFriendRequestResponse> getOfflineFriendRequests(Integer userId, LocalDateTime offlineTime) {
        QueryWrapper<FriendRequest> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(FriendRequest::getToUserId, userId)
                .eq(FriendRequest::getStatus, "pending")
                .gt(FriendRequest::getRequestTime,offlineTime);  // 只获取待处理的请求

        // 如果有离线时间，则只获取离线后的请求
        if (offlineTime != null) {
            queryWrapper.lambda().gt(FriendRequest::getRequestTime, offlineTime);
        }

        // 按时间排序
        queryWrapper.lambda().orderByAsc(FriendRequest::getRequestTime);

        List<FriendRequest> friendRequests = friendRequestMapper.selectList(queryWrapper);

        return friendRequests.stream().map(friendRequest -> {
            UserInfo userInfo = userMapper.selectById(friendRequest.getFromUserId());
            return new WebSocketFriendRequestResponse(
                    "friend_request",
                    friendRequest.getFromUserId(),
                    userInfo.getUserName(),
                    friendRequest.getReason(),
                    friendRequest.getStatus(),
                    friendRequest.getRequestTime()
            );
        }).collect(Collectors.toList());
    }

    @Override
    public void add(FriendRequest friendRequest) {
        // 设置初始状态和请求时间
        friendRequest.setStatus("pending");
        if (friendRequest.getRequestTime() == null) {
            friendRequest.setRequestTime(LocalDateTime.now());
        }
        friendRequestMapper.insert(friendRequest);
    }
}
